package com.zgm.ch04._5_1;

import java.security.MessageDigest;

import org.springframework.beans.factory.FactoryBean;

import org.springframework.beans.factory.InitializingBean;

/**
 * 当无法使用new操作符来新建对象（比如此例中的MessageDigest（MessageDigest为抽象类）对象），
 * 但又想将它们作为Spring的bean来使用时，FactoryBean是一个完美的
 * 解决方案。
 * @author zgm
 *
 */
public class MessageDigestFactoryBean implements FactoryBean, InitializingBean{
	private static final String DEFAULT_ALGORITHM = "MD5";
	
	private String algorithm = DEFAULT_ALGORITHM;
	private MessageDigest messageDigest;
	
	public Object getObject() throws Exception {
		return this.messageDigest.clone();
	}

	public Class getObjectType() {
		return MessageDigest.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public void afterPropertiesSet() throws Exception {
		this.messageDigest = MessageDigest.getInstance(this.algorithm);
	}

	public final String getAlgorithm() {
		return algorithm;
	}

	public final void setAlgorithm(String algorithm) {
		this.algorithm = algorithm;
	}

	
}
